#ifndef RS232DEVICE_H
#define RS232DEVICE_H

#include <QObject>
#include <QSerialPort>
#include <QDebug>
#include <QTimer>
#include <QThread>
#include "device.h"
#include <QJsonObject>

class SerialPortWriteThread : public QThread{
    Q_OBJECT
public:
    explicit SerialPortWriteThread(QObject *parent = nullptr){
    }

private:
    QSerialPort*    m_pSerialPort;
    QByteArray      m_ByteArrayData;

public:
    void SetQSerialPort(QSerialPort* pSerialPort){
        m_pSerialPort = pSerialPort;
    }

    void SetQByteArray(QByteArray byteArray){
        m_ByteArrayData = byteArray;
    }

public:
    void run() override {
        // 在这里执行你的线程任务
        const qint64 written = m_pSerialPort->write(m_ByteArrayData);
        m_pSerialPort->waitForBytesWritten();
    }
};

class RS232Device : public Device
{
    Q_OBJECT
public:
    explicit RS232Device(QObject *parent = nullptr);
    ~RS232Device();

    int GetSPort() const;
    void SetSPort(int port);
    QSerialPort::BaudRate GetBaud() const;
    void SetBaud(QSerialPort::BaudRate baud);
    QSerialPort::Parity GetParity() const;
    void SetParity(QSerialPort::Parity parity);
    QSerialPort::DataBits GetDatabits() const;
    void SetDatabits(QSerialPort::DataBits databits);
    QSerialPort::StopBits GetStopbits() const;
    void SetStopbits(QSerialPort::StopBits stopbits);
    QSerialPort::FlowControl GetFlowControl() const;
    void SetFlowControl(QSerialPort::FlowControl flowControl);

private:
    qint64 m_bytesToWrite = 0;

public:
    int openSerialPort();
    void closeSerialPort();

public:
    virtual Device* clone(Device* pDevice) override;

    virtual void writeData(const QVariant &data) override;
    virtual int initDevice() override;
    virtual void uninitDevice() override;

private slots:
    void readData();
    void handleError(QSerialPort::SerialPortError error);
    void handleBytesWritten(qint64 bytes);
    void handleWriteTimeout();

private:
    QSerialPort     *m_serial   = nullptr;
    QTimer          *m_timer    = nullptr;

public:
    virtual void writeXML(QXmlStreamWriter& writer) override;
    virtual void readFromXML(QXmlStreamReader& reader) override;

    virtual QString getClassName() override;
private:
    int                             m_nPort;
    QSerialPort::BaudRate           m_eBaud;
    QSerialPort::Parity             m_eParity;
    QSerialPort::DataBits           m_eDatabits;
    QSerialPort::StopBits           m_eStopbits;
    QSerialPort::FlowControl        m_eFlowcontrol;
};

#endif // RS232DEVICE_H
